package com.ade.warehouse.service;

import java.util.*;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import entity.Result;
import entity.StatusCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import util.IdWorker;

import com.ade.warehouse.dao.UserDao;
import com.ade.warehouse.pojo.User;
import util.JsonUtils;
import util.MockRedis;

/**
 * 服务层
 *
 * @author Administrator
 */
@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private IdWorker idWorker;

    @Resource
    private MockRedis jedisClient;

    @Value("${SESSION_EXPIRE}")
    private Integer SESSION_EXPIRE;


    public String login(String username, String password) {

        User user = userDao.findByName(username);
        //判断登录数据是否正确
        if (user == null) {
            return null;
        }
        if (!user.getPassword().equals(password)) {
            return null;
        }

        //如果正确则生成token，获取用户信息，保存到session中（redis缓存，模拟session）
        //写入格式：key：token value：用户信息
        String token = UUID.randomUUID().toString();
        user.setPassword(null);

        jedisClient.set("SESSION:" + token, JsonUtils.objectToJson(user));
        //设置session过期时间，配置文件中配置
        jedisClient.expire("SESSION:" + token, SESSION_EXPIRE);

        return token;
    }


    public Result getUserByToken(String token) {
        //根据token查询用户信息
        String user = jedisClient.get("SESSION:" + token);
        //若取不到表示过期
        if (StringUtils.isBlank(user)) {
           return new Result(false, StatusCode.ERROR, "用户登录已过期");
        }
        //重置过期时间
        jedisClient.expire("SESSION:" + token,SESSION_EXPIRE);

        HashMap<String,User> map=new HashMap<>();
        map.put("user",JsonUtils.jsonToPojo(user, User.class));
        return new Result(true, StatusCode.OK, "用户已登录",map);
    }

    public Result editUserByToken(String token,User sysUser) {
        jedisClient.set("SESSION:" + token,JsonUtils.objectToJson(sysUser));
        //重置过期时间
        jedisClient.expire("SESSION:" + token,SESSION_EXPIRE);

        HashMap<String,User> map=new HashMap<>();
        map.put("user",sysUser);
        return new Result(true, StatusCode.OK, "用户已登录",map);
    }
    



    /**
     * 查询全部列表
     *
     * @return
     */
    public List<User> findAll() {
        return userDao.findAll();
    }


    /**
     * 条件查询+分页
     *
     * @param whereMap
     * @param page
     * @param size
     * @return
     */
    public Page<User> findSearch(Map whereMap, int page, int size) {
        Specification<User> specification = createSpecification(whereMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return userDao.findAll(specification, pageRequest);
    }


    /**
     * 条件查询
     *
     * @param whereMap
     * @return
     */
    public List<User> findSearch(Map whereMap) {
        Specification<User> specification = createSpecification(whereMap);
        return userDao.findAll(specification);
    }

    /**
     * 根据ID查询实体
     *
     * @param id
     * @return
     */
    public User findById(String id) {
        return userDao.findById(id).get();
    }

    /**
     * 增加  名字要唯一
     *
     * @param user
     */
    public Boolean add(User user) {
        user.setId(idWorker.nextId() + "");
        User u = userDao.findByName(user.getName());
        if (u == null) {
            userDao.save(user);
            return true;
        }

        return false;

    }

    /**
     * 修改  名字要唯一
     *
     * @param user
     */
    public Boolean update(User user) {
        User u = userDao.findByName(user.getName());
        if (u == null) {
            userDao.save(user);
            return true;
        }
        return false;
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteById(String id) {
        userDao.deleteById(id);
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<User> createSpecification(Map searchMap) {

        return new Specification<User>() {

            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                // 
                if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                    predicateList.add(cb.like(root.get("id").as(String.class), "%" + (String) searchMap.get("id") + "%"));
                }
                // 
                if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                    predicateList.add(cb.like(root.get("name").as(String.class), "%" + (String) searchMap.get("name") + "%"));
                }
                // 
                if (searchMap.get("password") != null && !"".equals(searchMap.get("password"))) {
                    predicateList.add(cb.like(root.get("password").as(String.class), "%" + (String) searchMap.get("password") + "%"));
                }
                // 
                if (searchMap.get("email") != null && !"".equals(searchMap.get("email"))) {
                    predicateList.add(cb.like(root.get("email").as(String.class), "%" + (String) searchMap.get("email") + "%"));
                }
                // 
                if (searchMap.get("phone") != null && !"".equals(searchMap.get("phone"))) {
                    predicateList.add(cb.like(root.get("phone").as(String.class), "%" + (String) searchMap.get("phone") + "%"));
                }
                // 
                if (searchMap.get("mobile") != null && !"".equals(searchMap.get("mobile"))) {
                    predicateList.add(cb.like(root.get("mobile").as(String.class), "%" + (String) searchMap.get("mobile") + "%"));
                }
                // 
                if (searchMap.get("sex") != null && !"".equals(searchMap.get("sex"))) {
                    predicateList.add(cb.like(root.get("sex").as(String.class), "%" + (String) searchMap.get("sex") + "%"));
                }
                // 
                if (searchMap.get("pic") != null && !"".equals(searchMap.get("pic"))) {
                    predicateList.add(cb.like(root.get("pic").as(String.class), "%" + (String) searchMap.get("pic") + "%"));
                }
                // 
                if (searchMap.get("roleId") != null && !"".equals(searchMap.get("roleId"))) {
                    predicateList.add(cb.like(root.get("roleId").as(String.class), "%" + (String) searchMap.get("roleId") + "%"));
                }

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));

            }
        };

    }


}
